package com.sys.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bhudy.exception.SysExceptionCode;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author com.bhudy
 * @Description 处理成功返回给页面的类
 * @Date 2019-10-30 23:09:37
 */
public final class RequestUtils {

    private RequestUtils() {
    }

    public static Object printMapJson() {
        return RequestUtils.printMapJson(0, null, null, null);
    }

    /**
     * 根据code返回json数据
     */
    public static Object printMapJson(Object data) {
        return RequestUtils.printMapJson(0, null, null, data);
    }

    /**
     * 根据code返回json数据
     */
    public static Object printMapJson(String msg, Object data) {
        return RequestUtils.printMapJson(0, null, msg, data);
    }

    /**
     * 根据code返回json数据
     */
    public static Object printMapJson(int code, Object data) {
        return RequestUtils.printMapJson(code, null, null, data);
    }

    /**
     * 根据code返回json数据
     */
    public static Object printMapJson(int code, int count, Object data) {
        return RequestUtils.printMapJson(code, (long) count, null, data);
    }

    /**
     * 根据code返回json数据
     */
    public static Object printMapJson(int code, long count, Object data) {
        return RequestUtils.printMapJson(code, count, null, data);
    }

    /**
     * 根据code返回json数据
     */
    public static Object printMapJson(int code, Long count, String msg, Object data) {
        HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        resp.setContentType("text/json; charset=UTF-8");

        if (msg == null) {
            msg = SysExceptionCode.getMessage(code);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("message", msg);
        map.put("data", data);
        if (count != null) {
            map.put("count", count);
        }

        return JSON.toJSONString(map, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
    }

}